﻿// this page implements featured Dentists functionality
// Author: Wahaj Bangash                         Author : Wahaj Bangash
// Dated : May 30 ,2006                           Dated  : 07/07/07 (changes) Url Re-Writing Functionality Added

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using SiteManager;
using System.Data.SqlClient;
using System.IO;
using System.Xml;
using System.Text;

public partial class Dentist_FeaturedDentist : System.Web.UI.Page
{
    // creating an instance of manager class
    Manager manager = new Manager(true,"ConnectionString");
    protected localFunction obj = new localFunction();
    int pageNoNon = 1;
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            pageNoNon = Convert.ToInt32(Request.QueryString["pageNoNon"]);
            if (pageNoNon == 0)
                pageNoNon = 1;
        }
        catch
        {
            pageNoNon = 1;
        }
        //Response.Write("Hello");
        //Response.End();
        Master.keywordsContent = "featured dentists, best dentists, online dentists, find a dentist, ask a dentist, dentist list, dentists search, type of dentists, top dentists, rated dentists";
        Master.descriptionContent = "Featured Dentists – Find a dentist from our featured dentist list. Ask a dentist from our categorized featured dentist list online and you will get some best dentists of various categories, specialized dentist & highly rated dentists by our patients.";
        Master.titleContent = "Featured Dentists – Find A Featured dentist, Best dentist Online From dentist List";

        //cntPaging.PagingMode = PagingControl.Paging.pagingMode.QueryString;
        //cntPaging.CombinedPage = true;
        Master.TdRight = false;

        //Make TopLoginIMG Visible to display horizontal login box
        //Added: 29th Jan
        Master.TopLoginIMG = false;
        if (Request.QueryString.HasKeys())
        {
            if (!String.IsNullOrEmpty(Request.QueryString["catname"]))
            {
                string strCat = string.Empty;
                strCat = ReplaceUrl(Request.QueryString["catname"].ToString());
                
                #region  SEO Meta/Title fetch

                XmlDocument xmlDoc = new XmlDocument();
                string strFileName = string.Empty;

                strFileName = Request.PhysicalApplicationPath + @"app_data\dyn_content.xml";
                if (File.Exists(strFileName))
                {
                    xmlDoc.Load(strFileName);

                    XmlNodeList nodesList = xmlDoc.GetElementsByTagName("metas");

                    for (int i = 0; i < nodesList[0].ChildNodes.Count; i++)
                    {
                        if (nodesList[0].ChildNodes[i].Name.ToUpper() == "SPECIALTY")
                        {
                            //Response.Write(Request.QueryString["catname"].ToString().ToUpper() + " == " + getUrl(nodesList[0].ChildNodes[i].Attributes["name"].Value).ToUpper());

                            if (getUrl(nodesList[0].ChildNodes[i].Attributes["name"].Value).ToUpper().Equals(Request.QueryString["catname"].ToString().ToUpper()))
                            {
                                if (nodesList[0].ChildNodes[i].HasChildNodes)
                                {
                                    //Response.Write("C:" + nodesList[0].ChildNodes[i].ChildNodes.Count.ToString());

                                    for (int j = 0; j < nodesList[0].ChildNodes[i].ChildNodes.Count; j++)
                                    {
                                        XmlNode node = nodesList[0].ChildNodes[i].ChildNodes[j];
                                        switch (node.Name.ToUpper())
                                        {
                                            case "URL":
                                                //Response.Write("<p>URL:" + node.InnerText);
                                                break;
                                            case "TITLE":
                                                Master.titleContent = node.InnerText;
                                                //Response.Write("<p>TITLE:" + node.InnerText);
                                                break;
                                            case "DESCRIPTION":
                                                Master.descriptionContent = node.InnerText;
                                                //Response.Write("<p>DESCRIPTION:" + node.InnerText);
                                                break;
                                            case "KEYWORDS":
                                                Master.keywordsContent = node.InnerText;
                                                //Response.Write("<p>KEYWORDS:" + node.InnerText);
                                                break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                //else
                //{
                //    Response.Write("xml not found");
                //}
                xmlDoc = null;
                //Response.End();
                #endregion 
                if (!Page.IsPostBack)
                {
                    bindGrid(strCat);
                }
                else
                {
                    bindGrid(strCat);
                }

               
            }
        }
        else
        {

            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            ds = manager.ExecuteQuery("get_DentistFeatureSpecialty", "tbl");
            dt = ds.Tables[0];
            System.String vLink = string.Empty;
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    vLink = Session["strHttp"].ToString().Trim() + "Dentist/featured_Dentists_speciality_" + getUrl(dr["Name"]).ToString().Trim() + ".aspx";
                    specialtylist.Items.Add(new ListItem(dr["name"].ToString(), vLink));
                }
            }



            Master.fVisible = true;
        }
    }


    protected void grdRateDentist_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        double overallRate = 0;
        //Response.Write(e.Row.Cells[3].Text + "Hello");
        //Response.End();
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.Cells[3].Text == "&nbsp;")
            {
                e.Row.Cells[3].Text = 0.ToString();
            }
            overallRate = Convert.ToDouble(e.Row.Cells[3].Text);
           
            //HttpContext.Current.Response.Write("Hello Again");
            //HttpContext.Current.Response.End();
            if (overallRate > 100)
                overallRate = 100;

            ///K: 12 oct 2006
            ///if the Dentists are rated below rating limit they should be labeled as 'Not Rated'

            //e.Row.Cells[3].Text = Math.Round(overallRate, 2).ToString();

            float fRateLimit = Convert.ToSingle(ConfigurationManager.AppSettings["MinRatingLimit"].ToString());
            e.Row.Cells[3].Text = ((overallRate >= fRateLimit) ? Math.Round(overallRate, 2).ToString() : "Not Rated");
            e.Row.Cells[3].ForeColor = ((overallRate >= fRateLimit) ? System.Drawing.Color.Blue : System.Drawing.Color.Red);
            ///k: code ends   

        }
    }
    public string getPhoto(object photo, object sex)
    {
        string p = photo.ToString();
       // Response.Write("Photo");
        
        if (p.Length > 0)
        {
            if (File.Exists(Request.PhysicalApplicationPath + "\\images\\Dnt_images\\" + photo))
            {
                //return "<img height=\"100\" width=\"80\" src='../images/Dr_images/" + photo + "'>";
                //string str_path = manager.getThumbnaleImage("../images/Dr_images/" + photo, 80, 100, false, "");
                //return str_path;
                string str_path = getThumbnaleImageWithURLFormat(photo.ToString(), 80, 100, false, "", Session["strHTTP"].ToString());
                return str_path;
            }
            else
            {
                if (sex.ToString().ToLower() == "m")
                    return "<img height=\"100\" width=\"80\" src='" + Session["strHttp"].ToString() + "images/Dnt_images/silhouette-male.gif'>";
                else
                    return "<img height=\"100\" width=\"80\" src='" + Session["strHttp"].ToString() + "images/Dnt_images/silhouette--female.gif'>";
            //    if (sex.ToString().ToLower() == "m")
            //        return "<img height=\"100\" width=\"80\" src='../images/Dr_images/silhouette-male.gif'>";
            //    else
            //        return "<img height=\"100\" width=\"80\" src='../images/Dr_images/silhouette--female.gif'>";
            }
        }
        else
        {
            if (sex.ToString().ToLower() == "m")
                return "<img height=\"100\" width=\"80\" src='" + Session["strHttp"].ToString() + "images/Dnt_images/silhouette-male.gif'>";
            else
                return "<img height=\"100\" width=\"80\" src='" + Session["strHttp"].ToString() + "images/Dnt_images/silhouette--female.gif'>";
        }
    }
    public string getThumbnaleImageWithURLFormat(string imgName, int maxWidth, int maxHeight, bool saveImage, string savePath, string baseURL)
    {
        string s;
        double imgHeight, imgWidth;
        //Response.Write(imgName) ;
        s = Server.MapPath("~/images/Dnt_images/" + imgName);
        //Response.Write("</br>"+s);
        System.Drawing.Image currentImage = System.Drawing.Image.FromFile(s);
        imgHeight = currentImage.Height;
        imgWidth = currentImage.Width;
        if (imgWidth > maxWidth | imgHeight > maxHeight)
        {
            double deltaWidth = imgWidth - maxWidth;
            double deltaHeight = imgHeight - maxHeight;
            double scaleFactor;
            if (deltaHeight > deltaWidth)
                scaleFactor = maxHeight / imgHeight;
            else
                scaleFactor = maxWidth / imgWidth;
            imgWidth *= scaleFactor;
            imgHeight *= scaleFactor;
        }

        if (saveImage)
        {
            if (savePath == "")
                throw new Exception("must pass a file name");
            currentImage.GetThumbnailImage(Convert.ToInt32(imgWidth), Convert.ToInt32(imgHeight), null, IntPtr.Zero).Save(Server.MapPath(savePath));
            currentImage.Dispose();
        }
        //return currentImage.GetThumbnailImage(Convert.ToInt32(imgWidth), Convert.ToInt32(imgHeight), null, IntPtr.Zero);


        return ("<img src=\"" + baseURL + "images/Dnt_images/" + imgName + "\"" + " height=\"" + imgHeight + "\" width=\"" + imgWidth + "\" border='0' alt=''/>");
    }

    void bindGrid(System.String SpecialityName)
    {

        SqlParameter[] sqlParam = new SqlParameter[1];
        sqlParam[0] = new SqlParameter("@SpecialityID", SqlDbType.VarChar, 200);
        sqlParam[0].Value = SpecialityName;
       // cntPaging.SqlParameterList = sqlParam;
        DataSet ds_result = manager.ExecuteQuery("get_featureddentistsNew", sqlParam, "tbl_srch");
        string DoctorsNonFeaIds = GetDentistId(ds_result);
        DataSet ds = manager.ExecuteQuery(returnSql(GetPageId(pageNoNon, DoctorsNonFeaIds)), "tbl_drdet");
        if (ds.Tables[0].Rows.Count > 0)
        {

            grdRateDentist.DataSource = ds.Tables[0].DefaultView;
            if (pageNoNon > grdRateDentist.PageCount)
                grdRateDentist.PageIndex = 1;
            else
                grdRateDentist.PageIndex = pageNoNon;
            grdRateDentist.DataBind();
        }
        lblerr.Visible = false;
        trerror.Visible = false;
        trspec.Visible = false;
        trresult.Visible = true;

    }

    //protected override void Render(HtmlTextWriter writer)
    //{

    //   // litPaging.Text = cntPaging.RenderedHtml;
    //    base.Render(writer);
    //}



    protected string getUrl(object st)
    {
        return st.ToString().Replace(" & ", " and ").Replace(" ", "_").ToLower().Replace(",", "-or-");
    }
    protected string ReplaceUrl(object st)
    {
        return st.ToString().Replace("_and_", "_&_").Replace("_", " ").Replace("-or-", ",");
    }
    int getcPostion(int pageNo, string id)
    {
        string did = id; // Session["sDoctorsId"].ToString();
        int startNo = (pageNo - 1) * 10;
        int pos = 0;
        int pr = 0;
        //   Response.Write("startNo: " + startNo + "<BR>");
        for (int i = 0; i < startNo; i++)
        {
            pos = did.IndexOf(',', pr);
            //     Response.Write("<BR>Pos: " + pos);
            pr = pos + 1;
            if (did.IndexOf(',', pr) == -1)
            {
                pos = did.Length;
                break;
            }
        }
        return pos;
    }
    private int GetRecCount(string csvStr)
    {
        return csvStr.Split(new char[] { ',' }).Length;
    }
    public string UpdateQueryStringItem(System.Web.HttpRequest httpRequest, string queryStringKey, string newQueryStringValue)
    {
        StringBuilder NewURL = new StringBuilder();
        NewURL.Append(httpRequest.RawUrl);

        if (httpRequest.QueryString[queryStringKey] != null)
        {
            string OrignalSet = String.Format("{0}={1}", queryStringKey, httpRequest.QueryString[queryStringKey]);
            string NewSet = String.Format("{0}={1}", queryStringKey, newQueryStringValue);
            NewURL.Replace(OrignalSet, NewSet);
        }
        else if (httpRequest.QueryString.Count == 0)
        {
            NewURL.AppendFormat("?{0}={1}", queryStringKey, newQueryStringValue);
        }
        else
        {
            NewURL.AppendFormat("?{0}={1}", queryStringKey, newQueryStringValue);
        }
        return NewURL.ToString();
    }

    string GetPageId(int pageNo, string id)
    {
        string did = id; // Session["sDoctorsId"].ToString();

        int StartIndex = getcPostion(pageNo, id);
        int lastIndex = getcPostion(pageNo + 1, id);
        int totalRecs = GetRecCount(did);

        string ids = did.Substring(StartIndex, lastIndex - StartIndex);
        ids = ids.TrimEnd(',').TrimStart(',');
        int startingRec = 10 * (pageNo - 1) + 1;
        int endingRec = startingRec + (GetRecCount(ids) - 1);


        Normal.Text = "<table width='100%'><tr><td>Displaying " + startingRec + " to " + endingRec + " of " + totalRecs + "</td><td align='right'>";
                if (pageNo > 1)
                {
                    object page = pageNo - 1;
                    Normal.Text += "<a href='" + UpdateQueryStringItem(Page.Request, "pageNoNon", page.ToString()) + "'>Previous</a>";
                    //   Normal.Text += "<a href='SearchResultsDocs.aspx?pageNoNon=" + (pageNo - 1) + "&" + Request.QueryString.ToString() + "'>Previous</a>";
                }
                if (pageNo < (totalRecs / 10) || (pageNo == (totalRecs / 10) && (totalRecs % 10) != 0))
                {
                    object page = pageNo + 1;
                    Normal.Text += "&nbsp;&nbsp;&nbsp;<a href='" + UpdateQueryStringItem(Page.Request, "pageNoNon", page.ToString()) + "'>Next</a>";
                    //   Normal.Text += "&nbsp;&nbsp;&nbsp;<a href='SearchResultsDocs.aspx?pageNoNon=" + (pageNo + 1) + "&" + Request.QueryString.ToString() + "'>Next</a>";
                }
                Normal.Text += "</td></tr></table>";
               
       

        //     litPagingBelow.Text = litPaging.Text;
        return ids;
    }

    private string GetDentistId(DataSet ds)
    {
        string DentistIds = "";
        try
        {
            if (ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    if (i == 0)
                    { DentistIds = ds.Tables[0].Rows[i][7].ToString(); }
                    else
                    { DentistIds += "," + ds.Tables[0].Rows[i][7].ToString(); }
                }
            }
        }
        catch
        {
            DentistIds = "";
        }
        return DentistIds;
    }

    string returnSql(string ids)
    {
        //Response.Write(ids);
        Manager mgr = new Manager(true, "ConnectionString");
        string strSql = @"SELECT QU FROM DENTIST_FUNC_RATING()";

        SqlDataReader dr = mgr.ExecuteQuery(strSql);
        System.String orderClause = "";
        System.String AttachMiles = "";
        if (Session["Travel_Dis"].ToString() != "" && Session["Travel_Dis"].ToString() != null) //  to order the result first by Distance and then by rating Desc / to Calculate Miles
        {
            orderClause = "order by Distance ASC, Rate Desc";
            AttachMiles = " , (dbo.GetDistanceInMiles('" + Session["ZipCode"].ToString() + "','" + Session["City"].ToString() + "','" + Session["State"].ToString() + "',zipcodesearch)) as Distance";

        }
        else
        {
            orderClause = "order by Rate Desc";
            AttachMiles = ",'' as distance";
        }

        if (dr.Read())
        {
            strSql = @"select d.city, d.zipcode, sp.specialty as specialityName,
            (select tbl_DentistSubSpecialty.specialty from tbl_DentistSubSpecialty where
			 tbl_DentistSubSpecialty.specialty not in(Sp.specialty) and
			 tbl_DentistSubSpecialty.id=d.secondaryspecialityid)
             as SubSpec,
             rtrim((select name from tbl_states where stateId = d.state)) as state,
            CAST((" + dr[0].ToString() + @") as numeric(8,2)) as Rate,d.id as id,fname + ' ' + mname + ' ' + lname as [Name], d.City + ' ' + d.state + ' ' + d.ZipCode as Location, address1 + '<br>' + city + ', ' + state as address,
             Sp.specialty + isnull(', ' + (select tbl_DentistSubSpecialty.specialty from tbl_DentistSubSpecialty where
			tbl_DentistSubSpecialty.specialty not in(Sp.specialty) and
			 tbl_DentistSubSpecialty.id=d.secondaryspecialityid),'') as speciality,
            isnull(dp.website,'')as website,isnull(dp.photo,'') as photo,d.gender" + AttachMiles +
            " from tbl_Dentists d "
            + " left outer join tbl_DentistSubSpecialty s on s.id=d.secondaryspecialityid "
            + " left outer join tbl_dntpremium dp on dp.dnt_id=d.id "
            + " left outer join tbl_dentistspecialty sp on sp.id=D.specialityid "
             + " where  d.isdelete=0 and d.id in (" + ids + ") " + orderClause;

        }

        return strSql;
    }
}
